import yaml
from pathlib import Path
from typing import Dict, Any
from ..core.exceptions import ConfigurationError

class Config:
    DEFAULT_CONFIG = {
        'base_path': '~/.packagemanager',
        'repo_url': 'https://packages.example.com',
        'cache_dir': 'cache',
        'log_level': 'INFO',
        'max_concurrent_downloads': 3,
        'timeout': 30,
        'verify_ssl': True
    }

    def __init__(self, config_path: Path = None):
        self.config_data = self.DEFAULT_CONFIG.copy()
        if config_path:
            self.load_config(config_path)

    def load_config(self, config_path: Path) -> None:
        """加载配置文件"""
        try:
            with open(config_path, 'r', encoding='utf-8') as f:
                user_config = yaml.safe_load(f)
                if user_config:
                    self.config_data.update(user_config)
        except Exception as e:
            raise ConfigurationError(f"配置加载失败: {str(e)}")

    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        return self.config_data.get(key, default)

    def set(self, key: str, value: Any) -> None:
        """设置配置项"""
        self.config_data[key] = value

    def save(self, config_path: Path) -> None:
        """保存配置到文件"""
        try:
            with open(config_path, 'w', encoding='utf-8') as f:
                yaml.dump(self.config_data, f, allow_unicode=True)
        except Exception as e:
            raise ConfigurationError(f"配置保存失败: {str(e)}")